﻿using Dapper;
using Volo.Abp.DependencyInjection;
using YAKEJI.Abp.Database;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.SyncData;

public class GetApplyDepartment : WorkflowBase, IGetApplyDepartment, ITransientDependency
{
    private readonly IDatabaseConnectionProvider _connectionProvider;

    public GetApplyDepartment(IDatabaseConnectionProvider connectionProvider)
    {
        _connectionProvider = connectionProvider;
    }

    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        return new WorkflowOutput { Success = true };
        const string institutionCodeKey = "InstitutionCode";
        if (input.ContainsKey(institutionCodeKey))
        {
            var institutionCode = input.GetValueOrDefault(institutionCodeKey) as string;
            if (string.IsNullOrWhiteSpace(institutionCode)) throw new Exception("未找到医疗机构对应编码");
            var data = institutionCode switch
            {
                _ => await GetListByDataSourceAsync(),
            };
            return new WorkflowOutput
            {
                Success = true,
                Data = data
            };
        }
        return new WorkflowOutput
        {
            Success = false,
            Error = "未找到参数"
        };
    }
    private async Task<object> GetListByDataSourceAsync()
    {
        string path = @"D:\yapacs\data\datasource";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        string filePath = Path.Combine(path, @"Department.json");
        if (!File.Exists(filePath))
        {
            throw new Exception("数据文件不存在");
        }
        var context = await File.ReadAllTextAsync(filePath);
        var list = context.Deserialize<List<ApplyDepartment>>();
        return list;
    }
    /// <summary>
    /// 数据库方式获取
    /// </summary>
    /// <returns></returns>
    private async Task<IEnumerable<ApplyDepartment>> GetListByDatabaseAsync()
    {
        //const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=HIS;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False";
        const string connectionString = @"Server=192.168.2.82;Initial Catalog=HIS;User Id=sa;Password=pacs@1234;TrustServerCertificate=True";
        using var connection = _connectionProvider.GetDbConnection(connectionString, DatabaseType.SqlServer);
        if (connection.State == System.Data.ConnectionState.Closed)
        {
            connection.Open();
        }
        string sql = @"select Name,cast(Code as varchar(200)) as Code from pacs_view_apply_department";
        var departments = await connection.QueryAsync<ApplyDepartment>(sql);
        foreach (var department in departments)
        {
            sql = @"select Name,Code from pacs_view_apply_doctor where ApplyDepartment=@ApplyDepartment";
            var doctors = await connection.QueryAsync<ApplyDoctor>(sql, new { ApplyDepartment = department.Code });
            department.Doctors.AddRange(doctors);
        }
        return departments;
    }

    public class ApplyDepartment
    {
        public string Code { get; set; }
        public string Name { get; set; }

        public List<ApplyDoctor> Doctors { get; set; } = [];
    }
    public class ApplyDoctor
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }
}

